#include "../sour/TcpServer.hpp"
std::unordered_map<uint64_t, PtrConnection> _conns;//管理所有的连接
uint64_t connId = 0;
EventLoop base_loop;
LoopThreadPool* loopPool;
void ConnectionDestroy(const PtrConnection& conn)
{
    _conns.erase(conn->GetConnId());
}
void OnConnected(const PtrConnection& conn)
{
    DEBUG_LOG("NEW CONNECTION:%p", conn.get());
}
void OnMessage(const PtrConnection& conn, Buffer* buffer) 
{
    DEBUG_LOG("%s", buffer->ReadPosition());
    buffer->MoveReadOffset(buffer->ReadAbleSize());//将读偏移向后移动
    std::string str = "Hello world";
    conn->Send(str.c_str(), str.size());//发送数据，将数据放到发送缓冲区，启动写事件监控
    conn->Shutdown();
}
void NewConnection(int fd)
{
    connId++;
    PtrConnection conn(new Connection(loopPool->NextLoop(), connId, fd));
    conn->SetMessageCallBack(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetServerClosedCallBack(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallBack(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10);//添加定时任务，启动非活跃的连接销毁,超过timeout即视为非活跃
    conn->Established();//给channel设置事件回调，启动读监控，调用连接完成的回调：_connectedCallBack
    _conns.insert(std::make_pair(connId, conn));
    DEBUG_LOG("NEW ---------");
}
int main()
{
    loopPool = new LoopThreadPool(&base_loop);
    loopPool->SetThreadCount(2);
    loopPool->Create();
    Acceptor acceptor(&base_loop, 8500);
    //对监听套接字设置回调函数（获取新连接）
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));//设置可读事件的回调，回调中获取新连接，为新连接创建channel并添加监控
    acceptor.Listen();
    base_loop.StartEventLoop();
    return 0; 
}